package org.jeecg.modules.yusuan.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.fop.fo.pagination.Flow;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.JsonUtils;
import org.jeecg.modules.gudingzichan.entity.Gudingzichan;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.workflow.dto.FlowData;
import org.jeecg.modules.workflow.dto.ProcessNode;
import org.jeecg.modules.workflow.service.WorkFlowService;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.jeecg.modules.yusuan.entity.*;
import org.jeecg.modules.yusuan.service.ICaiwuBiaozhunService;
import org.jeecg.modules.yusuan.service.ICaiwuNzService;
import org.jeecg.modules.yusuan.service.ICaiwuYusuanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* @Description: caiwu_yusuan
* @Author: jeecg-boot
* @Date:   2020-06-15
* @Version: V1.0
*/
@RestController
@RequestMapping("/yusuan/nz")
@Slf4j
public class CaiwuNzController extends JeecgController<CaiwuNz, ICaiwuNzService> {
    @Autowired
    private ICaiwuNzService caiwuNzService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ICaiwuBiaozhunService caiwuBiaozhunService;
    @Autowired
    private WorkFlowService workFlowService;

    @GetMapping("/loadData")
    public Result<?> loadData(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,@RequestParam(required = false)String jingfeiType, @RequestParam( value = "deptId",required = false)String deptId) {
        if(StringUtils.isBlank(deptId)){
            String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
            deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();
        }
        Page<CaiwuNz> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<CaiwuNz> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CaiwuNz::getDeptId,deptId);
        if(StringUtils.isNotBlank(jingfeiType)){
            queryWrapper.eq(CaiwuNz::getJingfeiType,jingfeiType);
        }
        IPage<CaiwuNz> pageList =  caiwuNzService.page(page,queryWrapper);
        return Result.ok(pageList);
    }

    @GetMapping("/{jingfeiType}/count")
    public Result<?> jingfeiCount(@PathVariable String jingfeiType, @RequestParam Integer effective,
                                  @RequestParam( value = "deptId",required = false)String deptId){
        if(StringUtils.isBlank(deptId)){
            String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
            deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();
        }
        int count = this.caiwuNzService.jingfeiTypeCount(deptId,jingfeiType,effective);
        Result result = new Result();
        result.setResult(count);
        return result;
    }

    @GetMapping("/{recordId}/startFlow")
    public Result<?> startFlow(@PathVariable String recordId){
        String taskId = this.caiwuNzService.startFlow(recordId);

        return Result.ok(taskId);
    }

    @PostMapping("/{recordId}/apply")
    public Result<?> apply(@PathVariable String recordId, @RequestBody FlowData flowData){
        CaiwuNz caiwuNz = this.caiwuNzService.getById(recordId);
        this.caiwuNzService.startFlow2(caiwuNz,flowData);
        return Result.ok("操作成功");
    }

    @AutoLog(value = "我的申请-分页列表查询")
    @ApiOperation(value = "我的申请-分页列表查询", notes = "我的申请-分页列表查询")
    @GetMapping(value = "/myapplylist")
    public Result<?> myApplyList(CaiwuNz caiwuNz,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 @RequestParam( value = "deptId",required = false)String deptId) {
        if(StringUtils.isBlank(deptId)){
            String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
            deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();
        }
        caiwuNz.setDeptId(deptId);
        Page<CaiwuNz> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<CaiwuNz> iPage = caiwuNzService.myApplyList(page, user, caiwuNz);
//        if (iPage.getTotal() > 0) {
//            iPage.getRecords().forEach(record -> {
//                if (null != record.getEndTime()) {
//                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
//                } else {
//                    if (null != record.getAuditStatus()) {
//                        record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
//                    } else {
//                        record.setProcessStatus(ProcessKit.FLOW_STATUS_NOT_SUBMIT);
//                    }
//                }
//            });
//        }
        return Result.ok(iPage);
    }

    @AutoLog(value = "我的待办-分页列表查询")
    @ApiOperation(value = "我的待办-分页列表查询", notes = "我的待办-分页列表查询")
    @GetMapping(value = "/mytodolist")
    public Result<?> myTodoList(CaiwuNz caiwuNz,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                @RequestParam( value = "deptId",required = false)String deptId) {
//        if(StringUtils.isBlank(deptId)){
//            String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
//            deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();
//        }
        caiwuNz.setDeptId(deptId);
        Page<CaiwuNz> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<CaiwuNz> iPage = caiwuNzService.myTodoTasks(page, user, caiwuNz);
        return Result.ok(iPage);
    }

    @AutoLog(value = "我的已办-分页列表查询")
    @ApiOperation(value = "我的已办-分页列表查询", notes = "我的已办-分页列表查询")
    @GetMapping(value = "/mydonelist")
    public Result<?> myDoneList(CaiwuNz caiwuNz,
                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                @RequestParam( value = "deptId",required = false)String deptId) {
//        if(StringUtils.isBlank(deptId)){
//            String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
//            deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();
//        }
        caiwuNz.setDeptId(deptId);
        Page<CaiwuNz> page = new Page<>(pageNo, pageSize);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        IPage<CaiwuNz> iPage = caiwuNzService.myDoneTasks(page, user, caiwuNz);
//        if (iPage.getTotal() > 0) {
//            iPage.getRecords().forEach(record -> {
//                if (null != record.getEndTime()) {
//                    record.setProcessStatus(ProcessKit.FLOW_STATUS_END);
//                } else {
//                    record.setProcessStatus(ProcessKit.FLOW_STATUS_RUNNING);
//                }
//            });
//        }
        return Result.ok(page);
    }

    @GetMapping("/nextNodesList")
    public Result<?> nextNodesList(@RequestParam String taskId){

        FlowData flowData = workFlowService.nextNodesList(taskId);
        return Result.ok(flowData);
    }

    @AutoLog(value = "任务审批")
    @ApiOperation(value = "任务审批", notes = "任务审批")
    @PostMapping(value = "/completetask")
    public Result<?> completeTask(@RequestBody FlowData flowData) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        caiwuNzService.complateTask(loginUser, flowData);

        return Result.ok("操作成功");
    }

    @AutoLog(value = "任务审批")
    @ApiOperation(value = "任务审批", notes = "任务审批")
    @PostMapping(value = "/completeWithData")
    public Result<?> completeWithData(@RequestBody FlowData flowData) {
        CaiwuNz caiwuNz = flowData.getCaiwuNz();
        caiwuNzService.updateById(caiwuNz);
        List<Map<String,Object>> dataList = flowData.getDataList();
        if(org.apache.commons.lang.StringUtils.equals(caiwuNz.getJingfeiType(),"biaozhun")){
            List<CaiwuBiaozhun> list = new ArrayList<>();
            for(Map<String,Object> item:dataList){
                CaiwuBiaozhun biaozhun = (CaiwuBiaozhun) JsonUtils.toObject(JsonUtils.toJsonString(item),CaiwuBiaozhun.class);
                biaozhun.setEffective(0);
                list.add(biaozhun);
            }
            caiwuBiaozhunService.saveOrUpdateBatch(list);
        }

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        caiwuNzService.complateTask(loginUser, flowData);

        return Result.ok("操作成功");
    }

    @PostMapping("backToFirstNode")
    public Result backToFirstNode(@RequestBody FlowData flowData){

        workFlowService.backToFirstNode(flowData.getTaskId());
        caiwuNzService.updateById(new CaiwuNz().setId(flowData.getCaiwuNz().getId()).setProcessStatus(2));
        return Result.ok();
    }

    @PostMapping("addData/{jingfeiType}")
    public Result addData(@PathVariable String jingfeiType){
        String orgCode = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getOrgCode();
        String deptId = this.sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getOrgCode,orgCode)).getId();

        CaiwuNz caiwuNz = caiwuNzService.getOne(new LambdaQueryWrapper<CaiwuNz>().eq(CaiwuNz::getJingfeiType,jingfeiType).eq(CaiwuNz::getDeptId,deptId).orderByDesc(CaiwuNz::getCreateTime).last("limit 1"));
        if(null == caiwuNz){
            return Result.error("年度申请未审核完成");
        }
        caiwuNz.setId(null).setProcessStatus(null).setProcessInstanceId(null).setTaskId(null);
        caiwuNzService.save(caiwuNz);
        return Result.ok();
    }
}
